package com.yycx.module.file.provider.controller;

import com.yycx.common.base.vo.Ueditor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyf
 */
@Slf4j
@RequestMapping("/common/ueditor")
@RestController
public class UeditorController {


    @RequestMapping(value = "/cos")
    @CrossOrigin
    public Object server(String action, String callback, MultipartFile upfile, HttpServletResponse response) {
        Object result = null;
        switch (action) {
            case Ueditor.ACTION_CONFIG:
                String result1 = "";
                if (callback != null) {
                    result1 = callback + "(" + Ueditor.UEDITOR_CONFIG + ")";
                } else {
                    result1 = Ueditor.UEDITOR_CONFIG;
                }
                try {
                    //返回的十回调函数
                    response.getWriter().write(result1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case Ueditor.ACTION_UPLOADFILE:
            case Ueditor.ACTION_UPLOADVIDEO:
            case Ueditor.ACTION_UPLOADIMAGE:
                Ueditor ueditor = uploadPicForUeditor(upfile);
                result = ueditor;
                break;
            default:
        }
        return result;
    }

    public Ueditor uploadPicForUeditor(MultipartFile file) {
        Ueditor ueditor = new Ueditor();
        ueditor.setState(Ueditor.ACTION_SUCCESS);
        try {
            String s = "上传图片服务器后返回的地址";
            ueditor.setTitle(file.getName());
            ueditor.setOriginal(file.getOriginalFilename());
            ueditor.setUrl(s);
            return ueditor;
        } catch (Exception e) {
            ueditor.setState(Ueditor.ACTION_FAIL);
            e.printStackTrace();
        }
        return ueditor;
    }

}
